package com.scoy.honeymei.activity.mall;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.adapter.MallMain1Adapter;
import com.scoy.honeymei.adapter.MallMainAdapter;
import com.scoy.honeymei.adapter.tabadapter.ViewPagerAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.BannerBean;
import com.scoy.honeymei.bean.CatePlateBean;
import com.scoy.honeymei.bean.GoodsBean;
import com.scoy.honeymei.bean.ShopBean;
import com.scoy.honeymei.bean.ShopDetailBean;
import com.scoy.honeymei.custem.PageMe;
import com.scoy.honeymei.databinding.FragmentMallMainBinding;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.install.GridViewAdapter;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.MyUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MallFragment$
 * @Description:
 * @Author: GaoZhan
 * @CreateDate: 2019/8/30/0030$ 上午 9:20$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/8/30/0030$ 上午 9:20$
 * @UpdateRemark: 更新内容
 */
public class ShopMainActivity extends BaseActivity {


    private ShopMainActivity mContext;
    private FragmentMallMainBinding binding;
    private MallMain1Adapter mallAdapter;
    private int pageInt = 1;
    private String orderStr = "";
    private int shopId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = FragmentMallMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mContext = ShopMainActivity.this;
        shopId = getIntent().getIntExtra("shopId", 0);

        initNormal();

        getData();
        getGoodsList(1);

    }

    @Override
    public void initNormal() {

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorTrans);
        binding.titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        initRv();

        binding.fmmSearchTv.setOnClickListener(v -> {

            Intent intent0 = new Intent(mContext, GoodsListActivity.class);
            intent0.putExtra("cateId", 0);
            intent0.putExtra("pageType", 1);
            intent0.putExtra("shopId", shopId);
            startActivityForResult(intent0,1);
        });


        binding.norSrl.setOnRefreshListener(refreshLayout -> {

            refreshLayout.finishRefresh(1500);
            mallAdapter.clearData();
            getGoodsList(1);

        }).setOnLoadMoreListener(refreshLayout -> {
            refreshLayout.finishLoadMore(1500);
            getGoodsList(pageInt);
        });

        orderStr = "price";
        binding.fmmCheckpriceTv.setSelected(true);
        binding.fmmCheckpriceView.setSelected(true);
        binding.fmmCheckstarTv.setSelected(false);
        binding.fmmCheckstarView.setSelected(false);

        binding.fmmCheckpriceTv.setOnClickListener(v -> {
            if ("price".equals(orderStr)) return;
            orderStr = "price";
            binding.fmmCheckpriceTv.setSelected(true);
            binding.fmmCheckpriceView.setSelected(true);
            binding.fmmCheckstarTv.setSelected(false);
            binding.fmmCheckstarView.setSelected(false);
            binding.norSrl.autoRefresh();

        });
        binding.fmmCheckstarTv.setOnClickListener(v -> {
            if ("star".equals(orderStr)) return;
            orderStr = "star";
            binding.fmmCheckpriceTv.setSelected(false);
            binding.fmmCheckpriceView.setSelected(false);
            binding.fmmCheckstarTv.setSelected(true);
            binding.fmmCheckstarView.setSelected(true);
            binding.norSrl.autoRefresh();
        });

        binding.fmmToticketIv.setOnClickListener(v -> {
            Intent intentde = new Intent(mContext, CouponShopActivity.class);
            intentde.putExtra("shopId", shopId);
            startActivityForResult(intentde, 0x871);
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x871&&resultCode==0x871){
            setResult(0x871);
            finish();
        }
    }

    private void initRv() {
        mallAdapter = new MallMain1Adapter(mContext);
        GridLayoutManager glm = new GridLayoutManager(mContext, 2, RecyclerView.VERTICAL, false);
        binding.fmmGoodsRv.setLayoutManager(glm);
        binding.fmmGoodsRv.setAdapter(mallAdapter);
        mallAdapter.setOnOneClick(pos -> {
            //to goods
            GoodsBean item = mallAdapter.getItem(pos);
            int id = item.getId();
            Intent intentde = new Intent(mContext, GoodsDetailActivity.class);
            intentde.putExtra("goodsId", id + "");
            startActivityForResult(intentde, 0x871);
        });

    }

    private void getData() {
        HttpParams params = new HttpParams();
        params.put("shop_id", shopId);
        HpGo.newInstance().HttpGo(mContext, MyUrl.SHOP_DETAIL, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                ShopDetailBean sdBean = new Gson().fromJson(body, ShopDetailBean.class);
                List<BannerBean> bannerlist = sdBean.getBanner();
                List<CatePlateBean> category = sdBean.getCategory();
                ShopBean shopMes = sdBean.getDetail();
                PageMe.initBanner(mContext, binding.fmmBanner, bannerlist);
                initGrid(category);
            }
        });
    }


    private void getGoodsList(int myPage) {
        if (myPage == -1) {
            MyUtil.mytoast(mContext, "没有更多了~");
            return;
        }
        HttpParams params = new HttpParams();
        params.put("shop_id", shopId);
        params.put("page", myPage);
        //排序:price=价格从低到高,star=星级从高到底,不填则默认创建时间
        params.put("order", orderStr);
        HpGo.newInstance().HttpGo(mContext, MyUrl.STORE_HOT_GOODS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                List<GoodsBean> mlist = new Gson().fromJson(body, new TypeToken<List<GoodsBean>>() {
                }.getType());

                mallAdapter.addData(mlist);
                pageInt = mlist.size() == 0 ? -1 : myPage + 1;
                binding.nodataTv.setVisibility(mallAdapter.getData().size() == 0 ? View.VISIBLE : View.GONE);
            }
        });

    }


    @Override
    public void onStart() {
        super.onStart();
        binding.fmmBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        binding.fmmBanner.stopAutoPlay();
    }

    /**
     * 总的页数
     */
    private int pageCount;
    /**
     * 每一页显示的个数
     */
    private int pageSize = 8;
    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;


    private void initGrid(List<CatePlateBean> cateList) {
        if (cateList == null || cateList.size() == 0) {
            binding.fmmCateVp.setVisibility(View.GONE);
            return;
        } else {
            binding.fmmCateVp.setVisibility(View.VISIBLE);
            cateList.add(0, new CatePlateBean(0, "全部", "", shopId));
        }

        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(cateList.size() * 1.0 / pageSize);
        ArrayList<View> mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) LayoutInflater.from(mContext).inflate(R.layout.gridview, binding.fmmCateVp, false);
            GridViewAdapter gridViewAdapter = new GridViewAdapter(mContext, cateList, i, pageSize);
            gridView.setAdapter(gridViewAdapter);
            mPagerList.add(gridView);
            gridViewAdapter.setOnOneClick(pos -> {
                CatePlateBean cateBean = cateList.get(pos);
                Intent intent0 = new Intent(mContext, GoodsListActivity.class);
                intent0.putExtra("cateId", cateBean.getId());
                intent0.putExtra("pageType", 0);
                intent0.putExtra("shopId", shopId);
                intent0.putExtra("title", cateBean.getName());
                startActivity(intent0);
            });
        }

        //设置适配器
        binding.fmmCateVp.setAdapter(new ViewPagerAdapter(mPagerList));
        //设置圆点
        setOvalLayout();
        binding.mLlDot.setViewPager(binding.fmmCateVp);
    }


    /**
     * 设置圆点
     */
    public void setOvalLayout() {

     /*   for (int i = 0; i < pageCount; i++) {
            binding.mLlDot.addView(LayoutInflater.from(mContext).inflate(R.layout.btrmline, null));
        }
        // 默认显示第一页
        binding.mLlDot.getChildAt(0).findViewById(R.id.v_dot)
                .setBackgroundColor(getResources().getColor(R.color.colorMainRed));

        binding.fmmCateVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 取消圆点选中
                binding.mLlDot.getChildAt(curIndex)
                        .findViewById(R.id.v_dot)
                        .setBackgroundColor(getResources().getColor(R.color.colorMainGray3));
                // 圆点选中
                binding.mLlDot.getChildAt(position)
                        .findViewById(R.id.v_dot)
                        .setBackgroundColor(getResources().getColor(R.color.colorMainRed));
                curIndex = position;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/

    }


}
